#include "Cparser.h"

Cparser::Cparser(LPCTSTR szMemData)
{
	m_sMemData = szMemData;
}

Cparser::~Cparser(void)
{
}

void Cparser::SetMemData( string szMemData)
{
	m_sMemData = szMemData;
}

LRESULT Cparser::FindValue(string s, string e, string* sRet)
{
	GTools tools;
	LRESULT  hr = FindElement( s, e , sRet) ;
	int k = sRet->find(">");
	if ( k != string::npos)
	{
		*sRet = sRet->substr( 0, k);
	}
	*sRet = tools.replace_all( *sRet , "\'", "");
	*sRet = tools.replace_all( *sRet , "\"", "");
	return hr;
}

LRESULT Cparser::FindElement(string div0, string div1 , string* sRet )
{
	string div[3] = {div0, div1};
	int ret = 0 ;
	ret = FindHtml( m_sMemData ,div , ret );
	if(ret != string::npos ){
	   sRet->append( div[2] );
	}
	return ret;
}

static int   TOUPPER(int   c)   {   
	return   toupper(c);   
}   
static int   TOLOWER(int   c)   {   
	return   tolower(c);   
}  
LRESULT Cparser::FindHtml( string source, string* div, int start)
{
	int pos[2] = {string::npos, string::npos};
	string s;
	s.begin() = std::transform( source.begin(), source.end(),  source.begin(), TOLOWER );
	pos[0] = source.find(div[0] , start);
	if (pos[0] != string::npos  )
	{
		pos[1] = source.find( div[1], pos[0]);
		if (pos[1] != string::npos )
		{
			div[2] = source.substr( pos[0] +  (div[0].length()) , pos[1] - pos[0] -  (div[0].length()) );
		}else{
			div[2] = source.substr( pos[0] +  (div[0].length()) );
			pos[1] = (pos[0] + div[0].length() + div[2].length());
		}
	}
	return ( pos [1]);
}

LRESULT Cparser::FindPoint( string* keypoint)
{
	string::size_type p =  m_sMemData.find( *keypoint );
	if ( p != string::npos)
	{
		m_sMemData =  m_sMemData.substr( p );
		*keypoint = "" ;
		return (p );
	}else {
		return	p;
	}
}